import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import ReactDOM from 'react-dom';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import Editor from '@/utils/Editor';
import moment from 'moment';
import axios from 'axios';
import http from '@/utils/http';
import GridLayout from 'react-grid-layout';
import {
  Row,
  Col,
  Button,
  Input,
  Modal,
  message,
  Icon,
  Tag,
  Pagination,
  Form,
  Drawer,
  Tabs,
  Collapse,
  Select,
  TreeSelect,
  Table,
  Spin,
  Switch,
  DatePicker,
  Radio,
  Popconfirm,
} from 'antd';
import styles from './index.less';
import router from 'umi/router';
import UserSession from '@/UserSession';

const QuestionList = React.lazy(() => import('./question'));
const Slot = React.lazy(() => import('./slot'));
const dateFormat = 'YYYY/MM/DD';

const Search = Input.Search;
const TabPane = Tabs.TabPane;
const { TextArea } = Input;
const { Panel } = Collapse;
const Option = Select.Option;
const TreeNode = TreeSelect.TreeNode;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const confirm = Modal.confirm;
// fake data generator
const getItems = count =>
  Array.from({ length: count }, (v, k) => k).map(k => ({
    id: `item-${k}`,
    content: `item ${k}`,
  }));

// a little function to help us with reordering the result
const reorder = (list, startIndex, endIndex) => {
  const result = Array.from(list);
  const [removed] = result.splice(startIndex, 1);
  result.splice(endIndex, 0, removed);

  return result;
};

const grid = 8;

const getItemStyle = (isDragging, draggableStyle) => ({
  // some basic styles to make the items look a bit nicer
  userSelect: 'none',
  padding: 11,
  margin: `0 ${grid}px 0 0`,
  background: '#fefe',
  color: 'grey',
  borderRadius: '30px',
  border: '1px solid lightgray',
  lineHeight: '0px',
  cursor: 'move',
  // change background colour if dragging
  background: isDragging ? 'lightgreen' : '#fefe',

  // styles we need to apply on draggables
  ...draggableStyle,
});

const getListStyle = isDraggingOver => ({
  background: isDraggingOver ? 'lightblue' : '#fff',
  display: 'flex',
  padding: grid,
  overflow: 'auto',
});

@connect(({ editQa, loading }) => ({
  editQa,
  loading: loading.effects['editQa/fetchApi'],
}))
class EditQa extends Component {
  constructor(props) {
    super(props);
    let propQus = [];
    let firstQues = '';
    let categoryId = '';
    if (props.questions) {
      propQus = props.questions;
      firstQues = propQus[0];
      propQus.splice(0, 1);
    }
    if (props.categoryIds) {
      categoryId = props.categoryIds;
    }

    this.onDragEnd = this.onDragEnd.bind(this);
    this.state = {
      qaId: props.qaId ? props.qaId : '',
      visible: false,
      modalTitle: '',
      isAddApi: false,
      isAddSlot: false,
      placeholder: '',
      list: [],
      type: null,
      page: 1,
      limit: 5,
      apiNames: '',
      keys: '',
      total: 0,
      apiObj: {},
      isShowApiTag: true,
      question: '',
      childrenDrawer: false,
      isShowMore: 'none',
      suggestions: [],
      isShowSlot: false,
      questionIndex: null,
      overall: 1,
      expandIconPosition: 'right',
      answerArr: [
        {
          isDefault: true,
          content: '',
          answerType: 'richText',
          slotValues: [],
          isEdit: false,
        },
      ],
      answerArr_bak: [
        {
          isDefault: true,
          content: '',
          answerType: 'richText',
          slotValues: [],
          isEdit: false,
        },
      ],
      slotArr: [],
      slotDetailArr: [],
      treeData: [],
      loading: false,
      classVisible: false,
      linkData: [],
      classQuestion: '',
      classField: 'q',
      searchClass: '',
      classPage: '1',
      classPageSize: 10,
      relateQAs: [],
      qaStatus: true,
      isForever: true,
      from: '',
      to: '',
      startTime: new Date(),
      endTime: new Date(),
      endOpen: false,
      qaActiveKeys: [],
      shared: props.isShard,
      synchronous: true,
      relateList: [],
      questionIds: [],
      spinning: false,
      addLoading: true,
      isShowSimTitle: true,
      standardQus: firstQues,
      questionArr: propQus,
      isFirstQus: false,
      questionsTotal: 0,
      towQuestionArr: propQus,
      drawerLoading: true,
      towQuestionTotal: 0,
      searchVal: '',
      qusLimit: 10,
      apiId: '',
      addQustions: [],
      editQuestions: [],
      delQuestions: [],
      isTowDrawer: '',
      apiDataSource: [],
      count: 1,
      saveQaLoading: false,
      suggestionsLength: 0,
      historyDrawer: false,
      getHistoryLoading: false,
      historyDataSource: [],
      historyDataSourceTotal: 0,
      getHistoryPage: 1,
      getHistoryLimit: 10,
      img: '',
      imgHide: '',
      isNew: true,
      items: getItems(6),
      addType: props.addType ? props.addType : '',
      taskResultId: props.taskResultId ? props.taskResultId : '',
      unresolvedId: props.unresolvedId ? props.unresolvedId : '',
      unknownId: props.unknownId ? props.unknownId : '',
      commQus: '',
      addQuestions: [],
      categoryId: props.categoryIds,
      addSimqa: '',
    };
    this.columns = [
      {
        title: '问题',
        key: 'question',
        dataIndex: 'question',
      },
      {
        title: '分类',
        key: 'category',
        dataIndex: 'category',
      },
      {
        title: '操作',
        render: (text, item) => {
          return (
            <div>
              {this.state.relateQAs.indexOf(item.sid) === -1 ? (
                <Button type="primary" size="small" onClick={text => this.addLinkThis(item)} icon="link">关联</Button>
              ) : (
                <Button size="small" icon="link">已关联</Button>
              )}
            </div>
          );
        },
      },
    ];
    this.historyColumns = [
      {
        title: '问题',
        dataIndex: 'questions',
        key: 'questions',
        width: 'calc(40vw)',
        // render: aligns => (
        //   <div>
        //     <div>
        //       { aligns ? aligns.map((item, index) => {
        //         return <p key={index}>{item}</p>;
        //       }) : ""}
        //     </div>
        //   </div>
        // ),
      },
      {
        title: '回答',
        dataIndex: 'answers',
        key: 'answers',
        width: 'calc(40vw)',
        render: item => {
          if (item) {
            const b = item.map(val => {
              if (val.indexOf('img') != -1) {
                const a = val.replace('img', 'img style="max-width:100%"');
                return (
                  <div onClick={() => this.openGaller(a)}>
                    <div className={styles.hdbjB} dangerouslySetInnerHTML={{ __html: a }} />
                  </div>
                );
              }
              return (
                <div>
                  <div dangerouslySetInnerHTML={{ __html: val }} />
                </div>
              );
            });
            return b;
          }
        },
      },
      {
        title: '时间',
        dataIndex: 'time',
        key: 'time',
        width: 'calc(20vw)',
        render: dataIndex => {
          return moment(dataIndex).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        width: 'calc(20vw)',
        render: (text, recoder) => {
          switch (text) {
            case 'create':
              return (
                <Button type="primary" size="small">新建</Button>
              );
              break;
            case 'update':
              return (
                <Button type="primary" style={{ backgroundColor: 'grey', color: '#fff' }} size="small">更新</Button>
              );
              break;
            case 'remove':
              return (
                <Button type="primary" size="small" style={{ backgroundColor: 'lightred', color: '#fff' }}>删除</Button>
              );
              break;
          }
        },
      },
      {
        title: '操作人',
        dataIndex: 'operator',
        key: 'operator',
        width: 'calc(20vw)',
      },
    ];
  }

  componentDidMount() {
    this.initKnow(this.props.qaId);
  }

  componentWillReceiveProps(nextProps, nextContext) {
    // if (nextProps.qaId !== this.state.qaId && nextProps.qaId) {
    //   this.setState(
    //     {
    //       qaId: nextProps.qaId,
    //     },
    //     () => {
    //       this.getAnswerDetailByQaid(nextProps.qaId);
    //       this.getQuestionsByQaid(nextProps.qaId);
    //       this.getStandardQuestionByQaId(nextProps.qaId);
    //     }
    //   );
    // } else if (this.state.qaId === '' || this.state.qaId === undefined) {
    //   const standardQus = nextProps.questions[0];
    //   nextProps.questions.shift();
    //   this.setState({
    //     spinning: false,
    //     categoryId: nextProps.categoryIds === '' ? '' : nextProps.categoryIds,
    //     questionArr: nextProps.questions,
    //     standardQus,
    //   });
    // }
  }

  openGaller = item => {
    this.setState({
      img: item,
      a: true,
    });
  };

  initKnow = qaId => {
    this.getCategoryListJson();
    if (qaId) {
      this.setState(
        {
          qaId,
          isNew: false,
        },
        () => {
          this.getAnswerDetailByQaid(qaId);
          this.getQuestionsByQaid(qaId);
          this.getStandardQuestionByQaId(qaId);
        }
      );
    } else {
      this.setState(
        {
          isNew: true,
        },
        () => {
          // this.getQaIdByReq();
        }
      );
    }
  };

  delSlot = (e, index, name, ids) => {
    e.preventDefault();
    const arr = this.state.answerArr_bak;
    const slotList = this.state.slotArr;
    const slotDetailArr = this.state.slotDetailArr;
    for (const i of arr) {
      for (const j of i.slotValues) {
        if (j.slotName === name) {
          return message.error('该词槽被下面的答案引用，请删除/修改答案后尝试');
        }
      }
    }
    slotList.splice(index, 1);
    const newSlotDetailArr = slotDetailArr.filter(item => item.id !== ids);
    this.setState({
      slotArr: slotList,
      slotDetailArr: newSlotDetailArr,
    });
  };

  cleanApi = e => {
    e.preventDefault();
    this.setState({
      apiObj: {},
      isShowApiTag: false,
      isAddApi: false,
      apiId: '',
    });
  };

  addApi = () => {};

  handleCancel = () => {
    this.setState({ visible: false, searchType: '', keys: '' });
  };

  showModal = type => {
    this.setState(
      {
        visible: true,
        addLoading: true,
        keys: '',
      },
      () => {
        switch (type) {
          case 'api':
            this.fetchApiListByRobotId();
            break;
          case 'slot':
            this.fetchSlotListByRobotId();
            break;
        }
      }
    );
  };

  newCreate = () => {
    const type = this.state.type;
    switch (type) {
      case 'api':
        window.open('/knowledgeDesign/customApi');
        break;
      case 'slot':
        window.open('/knowledgeDesign/wordTroughManage');
        break;
    }
  };

  fetchApiListByRobotId = page => {
    const { dispatch, currentUser } = this.props;
    let newPage = this.state.page;
    const newLimit = this.state.limit;
    const newApiNames = this.state.apiNames;
    if (page) {
      newPage = page;
    }

    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/fetchApi',
        payload: {
          robotId: currentUser.robotId,
          page: newPage,
          limit: newLimit,
          apiNames: newApiNames,
        },
        callback: res => {
          this.setState({
            modalTitle: '添加API接口',
            placeholder: '请输入已有API接口',
            type: 'api',
            list: res.list,
            total: res.total,
            addLoading: false,
          });
        },
      });
    });
  };

  fetchSlotListByRobotId = page => {
    const { dispatch, currentUser } = this.props;
    let newPage = this.state.page;
    const newLimit = this.state.limit;
    const newKeys = this.state.keys;
    if (page) {
      newPage = page;
    }

    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/fetchSlot',
        payload: { robotId: currentUser.robotId, page: newPage, limit: newLimit, keys: newKeys },
        callback: res => {
          this.setState({
            modalTitle: '添加词槽',
            placeholder: '请输入已有词槽',
            type: 'slot',
            list: res.list,
            total: res.total,
            addLoading: false,
          });
        },
      });
    });
  };

  getApiDetailByApiId = id => {
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/fetchApiDetailById',
        payload: { apiId: id },
        callback: res => {
          this.setState(
            {
              apiObj: res,
            },
            () => {}
          );
        },
      });
    });
  };

  selected = item => {
    const type = this.state.type;
    switch (type) {
      case 'api':
        this.setState(
          {
            isAddApi: true,
            apiObj: item,
            visible: false,
            isShowApiTag: true,
            apiId: item.id,
            keys: '',
          },
          () => {
            this.getApiDetailByApiId(item.id);
          }
        );
        break;
      case 'slot':
        const arr = this.state.slotArr;
        if (arr.length >= 5) {
          return message.error('词槽不可大于5个，请删除重试');
        }

        const result = arr.some(items => {
          return items.name == item.name;
        });
        if (result) {
          return message.error('该词槽已存在');
        }
        arr.push(item);
        this.setState({
          isAddSlot: true,
          visible: false,
          slotArr: arr,
          keys: '',
        });
        break;
    }
  };

  modalSearch = val => {
    const type = this.state.type;
    this.setState(
      {
        searchType: type,
      },
      () => {
        switch (type) {
          case 'api':
            this.setState(
              {
                apiNames: val,
              },
              () => {
                this.fetchApiListByRobotId(1);
              }
            );
            break;
          case 'slot':
            this.setState(
              {
                keys: val,
              },
              () => {
                this.fetchSlotListByRobotId(1);
              }
            );
            break;
        }
      }
    );
  };

  slotAndApiSearch = val => {

    this.setState({
      keys: val.target.value,
    });
  };

  // 翻页
  fanye(e, a) {
    const type = this.state.type;
    if (a) {
      this.setState(
        {
          classPage: e,
        },
        () => {
          return this.fetchLinkData();
        }
      );
    }
    switch (type) {
      case 'api':
        this.setState(
          {
            page: e,
          },
          () => {
            this.fetchApiListByRobotId();
          }
        );
        break;
      case 'slot':
        this.setState(
          {
            page: e,
          },
          () => {
            this.fetchSlotListByRobotId();
          }
        );
        break;
    }
  }

  addQuestion = val => {
    this.setState({
      question: val.target.value,
    });
  };

  remove = k => {
    const { form } = this.props;
    const keys = form.getFieldValue('keys');
    if (keys.length === 1) {
      return;
    }

    form.setFieldsValue({
      keys: keys.filter(key => key !== k),
    });
  };

  add = val => {
    if (this.state.isShard) {
      return message.warn('共享的知识点不允许编辑添加标准问和相似问');
    }
    let arr = this.state.questionArr;
    let qus = this.state.standardQus;
    let array = this.state.addQuestions;
    const addQus = this.state.addQuestions;

    if (typeof val === 'object') {
      if (arr.length === 0 && !qus) {
        qus = val[0];
        val.shift();
        arr = arr.concat(val);
        array.push(val);
      } else {
        arr = arr.concat(val).reverse();
        array.push(val);
      }
    } else {
      if (val === qus) {
        return message.error(`该${val}在标准问中已存在，请修改再试`);
      }
      if (arr.indexOf(val) !== -1) {
        return message.error(`该相似问${val}已存在，请修改再试`);
      }
      if (!qus) {
        qus = val;
      } else {
        arr.unshift(val);
        array.push(val);
      }
    }
    this.setState({
      question: '',
      questionArr: arr,
      towQuestionArr: arr,
      standardQus: qus,
      page: 1,
      addQuestions: array,
      addSimqa: '',
    });
  };

  showChildrenDrawer = () => {
    const { qaId } = this.props;
    this.setState({
      childrenDrawer: true,
      isShowSimTitle: false,
      drawerLoading: false,
    });
    if (qaId) {
      this.getQuestionsByQaid(qaId, true);
      this.getStandardQuestionByQaId(qaId);
    }
  };

  onChildrenDrawerClose = () => {
    this.setState({
      childrenDrawer: false,
      isShowSimTitle: true,
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { keys, names } = values;
      }
    });
  };

  fixQuestion = (e, val, index) => {
    let newIndex = index + (this.state.page - 1) * 10;
    const arr = this.state.questionArr;
    arr[newIndex] = e.target.value;
    this.setState({
      questionArr: arr,
      towQuestionArr: arr,
    });
  };

  showSlot = e => {
    this.setState({
      isShowSlot: true,
    });
  };

  hideSlot = e => {
    this.setState({
      question: e.target.value,
      isShowSlot: false,
    });
  };

  showQuestionSlot = (e, index) => {
    this.setState({
      questionIndex: index,
    });
  };

  hideQuestionSlot = (e, index) => {
    this.setState({
      questionIndex: null,
    });
  };

  setAsk = (val, index) => {
    const { form } = this.props;
    const keys = form.getFieldValue('keys');
    const keys0 = keys[0];
    keys[0] = val;
    keys[index] = keys0;
    form.setFieldsValue({
      keys,
    });
  };

  enterHistory = () => {
    window.open('/knowledge/amendantRecord');
  };

  callback(key, index) {
    const arr = this.state.answerArr;
    arr[index].answerType = key;
    this.setState({
      answerArr: arr,
    });
  }

  onEditQa = (index, type) => {
    const arr = this.state.answerArr;
    if (index !== -1 && type !== 'save') {
      arr[index].isEdit = !arr[index].isEdit;
      this.setState({
        answerArr: arr,
      });
    }
    switch (type) {
      case 'save':
        this.setDefaultAnswer(index);
        break;
      case 'del':
        this.delDefaultAnswer(index, 'del');
        break;
      case 'add':
        this.addAnswer();
      case 'edit':
        this.editAnswer(index);
        break;
      case 'cancel':
        this.delDefaultAnswer(index, 'cancel');
        break;
    }
  };

  addSlotToQuestion = (val, index) => {
    if (index !== '') {
      const { form } = this.props;
      const keys = form.getFieldValue('keys');
      const value = `${keys[index]}<${val}>`;
      keys[index] = value;
      form.setFieldsValue({
        keys,
      });
    } else {
      const value = `${this.state.question}<${val}>`;
      this.setState({
        question: value,
      });
    }
  };

  setDefaultAnswer = index => {
    const answer = this.state.answerArr;
    const answer_bak = this.state.answerArr_bak;
    const type = answer[index].answerType;
    const slots_bak = answer_bak[index].slotValues;
    const isDefault = answer[index].isDefault;
    answer[index].slotValues = slots_bak;
    const slots = answer[index].slotValues;
    if (slots.length === 0 && !isDefault) {
      return message.error('词槽答案词槽不允许为空，请添加词槽再保存');
    }
    if (slots.length === 1 && !isDefault) {
      for (const i of slots) {
        if (i.values.length == 0) {
          return message.error('词槽答案词槽不允许为空，请添加词槽再保存');
        }
      }
    }
    let content = '';
    const con = `content${index}`;
    switch (type) {
      case 'richText':
        content = this.refs[con].getUeditorContent();
        break;
      case 'text':
        content = this.state.textValue;
        break;
    }
    answer[index].content = content;
    answer[index].isEdit = !answer[index].isEdit;
    const qaActiveKeys = this.state.qaActiveKeys;
    qaActiveKeys.push(answer.length.toString());
    this.setState({
      answerArr: answer,
      qaActiveKeys,
    });
  };

  delDefaultAnswer = (index, type) => {
    const arr_bak = this.state.answerArr_bak;
    const arr = this.state.answerArr;
    const isDefault = arr_bak[index].isDefault;
    const isEdit = arr_bak[index].isEdit;
    switch (type) {
      case 'del':
        if (!isDefault) {
          arr.splice(index, 1);
          this.setState({
            answerArr_bak: arr,
            answerArr: arr,
          });
        }
        break;
      case 'cancel':
        if (!isDefault) {
          if (!isEdit) {
            arr_bak.splice(index, 1);
            arr.splice(index, 1);
            this.setState({
              answerArr_bak: arr_bak,
              answerArr: arr,
            });
          }
        }
        break;
    }
  };

  getTextValue = e => {
    const value = e.target.value;
    this.setState({
      textValue: value,
    });
  };

  addAnswer = () => {
    const answers = this.state.answerArr;
    const answer_bak = this.state.answerArr_bak;
    let arr = [];
    let arr_bak = [];
    arr = arr.concat(answers);
    arr_bak = arr_bak.concat(answer_bak);
    arr.unshift({
      isDefault: false,
      content: '',
      answerType: 'richText',
      slotValues: [],
      isEdit: false,
    });
    arr_bak.unshift({
      isDefault: false,
      content: '',
      answerType: 'richText',
      slotValues: [],
      isEdit: false,
    });
    const slotList = this.state.slotArr;
    for (const i of slotList) {
      this.fetchSlotDetailBySlotId(i._id, i.name);
    }
    this.setState({
      answerArr: arr,
      answerArr_bak: arr_bak,
      qaActiveKeys: [],
    });
  };

  editAnswer = index => {
    const slotList = this.state.slotArr;
    for (const i of slotList) {
      this.fetchSlotDetailBySlotId(i._id, i.name, index);
    }
  };

  fetchSlotDetailBySlotId = (id, name, index) => {
    const that = this;
    const { dispatch } = that.props;
    that.setState({
      slotDetailArr: [],
    });
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/getDictItemFromSlotId',
        payload: { slotId: id },
        callback: res => {
          res[0].name = name;
          res[0].id = id;

          const arr = that.state.slotDetailArr;
          let newArr = [];
          const result = arr.some(items => {
            return items.name == res[0].name;
          });
          // if(!result){
          newArr = newArr.concat(arr);
          newArr = newArr.concat(res);
          if (index !== undefined) {
            for (const o of that.state.answerArr[index].slotValues) {
              for (const j of newArr) {
                if (o.slotName === j.name) {
                  j.values = o.values;
                }
              }
            }
          } else {
            for (const i of that.state.answerArr) {
              for (const o of i.slotValues) {
                for (const j of newArr) {
                  if (o.slotName === j.name) {
                    j.values = o.values;
                  }
                }
              }
            }
          }
          this.setState({
            slotDetailArr: newArr,
          });
        },
        // }
      });
    });
  };

  addSlotForSelect = (value, index, slotIndex, _id, newName) => {
    const arr = this.state.answerArr_bak;
    const oldSlotArr = arr[index].slotValues;
    const newArr = oldSlotArr.filter(item => item.slotName === newName);
    if (newArr.length > 0) {
      oldSlotArr[slotIndex].values = value;
    } else {
      oldSlotArr.push({
        id: _id,
        values: value,
        slotName: newName,
      });
    }
    this.setState({
      answerArr_bak: arr,
    });
  };

  editSlotByUnSelect = (value, index) => {
    const arr = this.state.answerArr_bak;
    const slots = arr[index].slotValues;
    slots.forEach(item => {
      item.values.forEach((s, j) => {
        if (s === value) {
          item.values.splice(j, 1);
        }
      });
    });
    this.setState({
      answerArr_bak: arr,
    });
  };

  addLinkQa = () => {
    this.setState({
      classVisible: true,
    });
    this.fetchLinkData();
  };

  getCategoryListJson = () => {
    const { dispatch } = this.props;
    const obj = {};
    // dispatch({
    //   type: 'editQa/categoryListJson',
    //   payload: obj,
    //   callback: res => {
    //     const arr = [];
    //     arr.push(res[0]);
    //     this.setState({
    //       treeData: arr,
    //     });
    //   },
    // });

    const headData = {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${UserSession.getToken()}`,
    };
    return new Promise(resolve => {
      axios
        .post('/cloud/knowledge/base/category/getCategoryTree', obj, { headers: headData })
        .then(res => {
          const arr = [];
          if (res.data.data) {
            if (this.state.isShard) {
              for (let i of res.data.data) {
                arr.push(i);
              }
            } else {
              arr.push(res.data.data[0]);
            }
            this.setState({
              treeData: arr,
            });
          }
        });
    });
  };

  renderTreeNodes = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.text} key={item.data.path} value={item.id} id={item.id}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.text} key={item.data.path} value={item.id} id={item.id} />;
    });
  };

  onTreeChange = (value, label, extra) => {

    this.setState({ categoryId: value });
  };

  fetchLinkData = () => {
    this.setState(
      {
        loading: true,
      },
      () => {
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'editQa/linkBoxJson',
            payload: {
              robotId: currentUser.robotId,
              question: this.state.standardQus,
              field: this.state.classField,
              query: this.state.searchClass,
              page: this.state.classPage,
              limit: this.state.classPageSize,
            },
            callback: res => {
              const arr = res.qaList;
              const suggestionsLength = res.suggestList.length;
              this.setState({
                total: res.total,
                linkData: arr,
                loading: false,
                suggestionsLength,
              });
            },
          });
        });
      }
    );
  };

  classHandleCancel = () => {
    this.setState({
      classVisible: false,
      searchClass: '',
    });
  };

  addLinkThis = item => {
    let arr = [];
    let relateArr = [];
    arr = arr.concat(this.state.relateQAs);

    if (arr.length >= 10) {
      return message.error('关联问最多添加10条');
    }
    arr.unshift(item.sid);
    relateArr = relateArr.concat(this.state.relateList);
    relateArr.unshift(item);
    this.setState(
      {
        relateQAs: arr,
        relateList: relateArr,
      },
      () => {}
    );
  };

  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        classPage: current,
        classPageSize: pageSize,
      },
      () => {
        this.fetchLinkData();
      }
    );
  };

  classSelectChange = e => {
    this.setState(
      {
        classField: e,
      },
      () => {
        this.fetchLinkData();
      }
    );
  };

  searchClass = e => {

    this.setState(
      {
        searchClass: e,
        classPage: 1,
      },
      () => {
        this.fetchLinkData();
      }
    );
  };

  onDelRelateQa = (index, qa) => {
    const arr = this.state.relateList;
    const { relateQAs } = this.state;
    for (let i = 0; i < relateQAs.length; i++) {
      if (relateQAs[i] === qa.sid) {
        relateQAs.splice(i, 1);
      }
    }
    arr.splice(index, 1);
    this.setState({
      relateList: arr,
      relateQAs,
    });
  };

  onSetRelateQa = index => {
    const arr = this.state.relateList;
    if (index !== 0) {
      arr[index] = arr.splice(index - 1, 1, arr[index])[0];
    } else {
      arr.push(arr.shift());
    }
    this.setState({
      relateList: arr,
    });
  };

  onChangeQaStatus = checked => {
    this.setState({
      qaStatus: checked,
    });
  };

  onChangeQaIsForever = e => {
    this.setState({
      isForever: e.target.value,
    });
  };

  onStartChange = (value, dateString) => {
    this.onDateChange('startTime', value, dateString);
  };

  onEndChange = (value, dateString) => {
    this.onDateChange('endTime', value, dateString);
  };

  handleStartOpenChange = open => {
    if (!open) {
      this.setState({ endOpen: true });
    }
  };

  handleEndOpenChange = open => {
    this.setState({ endOpen: open });
  };

  onDateChange = (field, value, dateString) => {
    this.setState({
      [field]: value,
    });
    switch (field) {
      case 'startTime':
        this.setState({
          from: dateString,
        });
        break;
      case 'endTime':
        this.setState({
          to: dateString,
        });
        break;
    }
  };

  saveQa(categoryId) {
    let re = new RegExp('^[ ]+$');
    let url = '';
    let obj = {};
    let taskResultId = null;

    switch (this.state.addType) {
      case 'recommend':
        url = '/learn/knowledge/recommend/question/newQa';
        taskResultId = this.state.taskResultId;
        break;
      case 'cluster':
        url = '/learn/knowledge/cluster/question/newQa';
        taskResultId = this.state.taskResultId;
        break;
      default:
        url = '/cloud/knowledge/base/saveQa';
    }
    let questionList = [];
    questionList = this.state.questionArr;
    function isNull(str) {
      if (str == '') {
        return true;
      }
      var regu = '^[ ]+$';
      var re = new RegExp(regu);
      return re.test(str);
    }
    if (questionList.length === 0 && isNull(this.state.standardQus)) {
      return message.error('问题不能为空或仅为空格');
    }

    const { dispatch } = this.props;
    const { apiDataSource } = this.state;
    const arr = this.state.relateList;
    const newArr = [];
    for (const i of arr) {
      if (i.sid) {
        newArr.push(i.sid);
      } else {
        newArr.push(i.id);
      }
    }

    if (newArr.length > 11) {
      message.error('关联问不能超过10条');
      return false;
    }

    if (apiDataSource.length > 0) {
      let flog = false;
      for (const i of apiDataSource) {
        delete i.key;
        Object.keys(i).map((keyItem, j) => {
          if (i[keyItem] === '') {
            flog = true;
            switch (keyItem) {
              case 'slotKey':
                return message.error('词槽和请求字段对应关系中词槽不可为空');
                break;
              case 'apiFieldId':
                return message.error('词槽和请求字段对应关系中请求字段不可为空');
                break;
            }
          }
        });
      }
      if (flog) {
        return false;
      }
    }

    for (let i = 0; i < questionList.length; i++) {
      if (isNull(questionList[i])) {
        return message.info('问题不能为空或者仅为空格');
      }
    }

    if (!isNull(this.state.standardQus)) {
      if (questionList.indexOf(this.state.standardQus) != -1) {
        return message.info(this.state.standardQus + '问题已存在');
      }
      questionList.unshift(this.state.standardQus);
    } else {
      return message.info('问题不能为空或者仅为空格');
    }

    const slotIdArr = [];
    for (const i of this.state.slotArr) {
      if (i.id) {
        slotIdArr.push(i.id);
      } else {
        slotIdArr.push(i._id);
      }
    }
    let from = '';
    let to = '';
    if (!this.state.isForever) {
      if (this.state.from.indexOf('-') === -1) {
        from =
          this.state.from !== ''
            ? moment(parseInt(this.state.from)).format('YYYY-MM-DD')
            : moment(this.state.startTime === '' ? new Date() : this.state.startTime).format(
                'YYYY-MM-DD'
              );
      } else {
        from = this.state.from;
      }
      if (this.state.to.indexOf('-') === -1) {
        to =
          this.state.to !== ''
            ? moment(parseInt(this.state.to)).format('YYYY-MM-DD')
            : moment(this.state.endTime === '' ? new Date() : this.state.endTime).format(
                'YYYY-MM-DD'
              );
      } else {
        to = this.state.to;
      }
    }
    for (let i = 0; i < this.state.answerArr.length; i++) {
      if (!this.state.answerArr[i].isEdit) {
        if (!this.state.answerArr[i].answerType !== 'text') {
          const con = `content${i}`;
          this.state.answerArr[i].content = this.refs[con].getUeditorContent();
        } else {

        }
      }
    }

    if (this.state.qaId) {
      obj = {
        unresolvedId: this.state.unresolvedId,
        unknownId: this.state.unknownId,
        apiId: this.state.apiId,
        slots: slotIdArr,
        relateQAs: newArr,
        categoryId: this.state.categoryId == '' ? 'root' : this.state.categoryId,
        answers: this.state.answerArr,
        qaId: this.state.qaId,
        questions: questionList,
        isSharedQA: this.state.isShard,
        isSynchronous: false,
        disabled: !this.state.qaStatus,
        isForever: this.state.isForever,
        from,
        to,
        slotAndApi: apiDataSource,
        isNew: this.state.isNew,
        taskResultId,
      };
    } else {
      obj = {
        unresolvedId: '',
        unknownId: '',
        apiId: this.state.apiId,
        slots: slotIdArr,
        relateQAs: newArr,
        categoryId: this.state.categoryId == '' ? 'root' : this.state.categoryId,
        answers: this.state.answerArr,
        questions: questionList,
        isSharedQA: false,
        isSynchronous: false,
        disabled: !this.state.qaStatus,
        isForever: this.state.isForever,
        from:
          this.state.from.length === 13
            ? moment(parseInt(this.state.from)).format('YYYY-MM-DD')
            : moment(this.state.startTime).format('YYYY-MM-DD'),
        to:
          this.state.to.length === 13
            ? moment(parseInt(this.state.to)).format('YYYY-MM-DD')
            : moment(this.state.endTime).format('YYYY-MM-DD'),
        slotAndApi: apiDataSource,
        qaId: this.state.qaId,
        isNew: this.state.isNew,
      };
    }

    // this.reqRef = requestAnimationFrame(() => {
    //   dispatch({
    //     type: 'editQa/saveKp',
    //     payload: obj,
    //     callback: res => {
    //       if (res.msg) {
    //         message.info(res.msg);
    //       } else {
    //         message.info('保存成功');
    //       }
    //       this.setState(
    //         {
    //           relateQAs: [],
    //           saveQaLoading: false,
    //         },
    //         () => {
    //           this.props.onClose();
    //         }
    //       );
    //     },
    //   });
    // });

    const headData = {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${UserSession.getToken()}`,
    };
    this.setState({
      saveQaLoading: true,
    });
    axios.post(url, obj, { headers: headData }).then(ret => {
      let res = null;
      if (ret.data.data) {
        res = ret.data.data;
      } else {
        res = ret.data;
      }
      if (res.msg) {
        message.info(res.msg);
      } else {
        message.info('保存成功');
      }
      this.setState(
        {
          relateQAs: [],
          saveQaLoading: false,
        },
        () => {
          this.props.onClose();
        }
      );
    });
  }

  cancelSaveQa = () => {
    this.setState(
      {
        relateQAs: [],
      },
      () => {
        this.props.onClose();
      }
    );
  };

  checkStatus = status => {
    if (status === 401) {
      localStorage.clear();
      window.g_app._store.dispatch({
        type: 'login/logout',
      });
      return;
    }
    // environment should not be used
    if (status === 403) {
      router.push('/exception/403');
      return;
    }
    if (status <= 504 && status >= 500) {
      router.push('/exception/500');
      return;
    }
    if (status >= 404 && status < 422) {
      router.push('/exception/404');
    }
  };

  getAnswerDetailByQaid = qaId => {
    const { dispatch } = this.props;

    const headData = {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${UserSession.getToken()}`,
    };
    return new Promise(resolve => {
      axios
        .post('/cloud/knowledge/base/getKnowledgeDetail', { id: qaId }, { headers: headData })
        .then(ret => {
          let res = null;
          if (ret.data.code) {
            this.checkStatus(ret.data.code);
          }
          if (ret.data.data) {
            res = ret.data.data;
            const startTime = !res.enableTime.from === true ? '' : res.enableTime.from;
            const endTime = !res.enableTime.to === true ? '' : res.enableTime.to;
            if (res.apiId) {
              this.getApiDetailByApiId(res.apiId);
            }
            this.setState(
              {
                categoryId: res.categoryId,
                qaStatus: !res.disabled,
                apiId: !res.apiId === true ? '' : res.apiId,
                // apiObj: !res.api===true?'':res.api,
                isForever: res.enableTime.isForever,
                from: !res.enableTime.from === true ? '' : res.enableTime.from,
                to: !res.enableTime.to === true ? '' : res.enableTime.to,
                slotArr: !res.slotList === true ? [] : res.slotList,
                isAddSlot: !res.slotList === true ? false : res.slotList.length > 0,
                isAddApi: !res.apiId !== true,
                relateList: !res.relateList === true ? [] : res.relateList,
                shared: !res.shared === true ? false : res.shared,
                synchronous: !res.synchronous === true ? false : res.synchronous,
                startTime,
                endTime,
                apiDataSource: res.slotAndApi,
                // isShard: res.shared,
              },
              () => {
                this.getJsonAnswerByQaId(this.state.qaId);
              }
            );
          } else {
            return false;
          }
        });
    });
    // this.reqRef = requestAnimationFrame(() => {
    //   dispatch({
    //     type: 'editQa/getDetailByQaid',
    //     payload: { id: qaId },
    //     callback: res => {
    //       const startTime = !res.enableTime.from === true ? '' : res.enableTime.from;
    //       const endTime = !res.enableTime.to === true ? '' : res.enableTime.to;
    //       if (res.apiId) {
    //         this.getApiDetailByApiId(res.apiId);
    //       }
    //       this.setState(
    //         {
    //           categoryId: res.categoryId,
    //           qaStatus: !res.disabled,
    //           apiId: !res.apiId === true ? '' : res.apiId,
    //           // apiObj: !res.api===true?'':res.api,
    //           isForever: res.enableTime.isForever,
    //           from: !res.enableTime.from === true ? '' : res.enableTime.from,
    //           to: !res.enableTime.to === true ? '' : res.enableTime.to,
    //           slotArr: !res.slotList === true ? [] : res.slotList,
    //           isAddSlot: !res.slotList === true ? false : res.slotList.length > 0,
    //           isAddApi: !res.apiId !== true,
    //           relateList: !res.relateList === true ? [] : res.relateList,
    //           shared: !res.shared === true ? false : res.shared,
    //           synchronous: !res.synchronous === true ? false : res.synchronous,
    //           startTime,
    //           endTime,
    //           apiDataSource: res.slotAndApi,
    //         },
    //         () => {
    //           this.getJsonAnswerByQaId(this.state.qaId);
    //         }
    //       );
    //     },
    //   });
    // });
  };

  getQuestionsByQaid = (qaId, isTowDrawer) => {
    const { dispatch } = this.props;
    let limitNum = 21474836;

    if (isTowDrawer) {
      limitNum = this.state.qusLimit;
    }

    const headData = {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${UserSession.getToken()}`,
    };
    return new Promise(resolve => {
      axios
        .post(
          '/cloud/knowledge/base/getAlikeQuestionList',
          { id: qaId, limit: limitNum, page: this.state.page, search: this.state.searchVal },
          { headers: headData }
        )
        .then(ret => {
          if (ret.data.code) {
            this.checkStatus(ret.data.code);
          }
          if (ret.data.data) {
            const res = ret.data.data;
            const arr = [];
            for (const i of res.list) {
              arr.push(i.question);
            }
            for (let i of this.state.addQuestions) {
              arr.unshift(i);
            }
            if (isTowDrawer) {
              if (this.state.searchVal) {
                this.setState({
                  towQuestionArr: arr,
                  towQuestionTotal: res.total,
                  drawerLoading: false,
                  isTowDrawer,
                });
              } else {
                this.setState({
                  // questionArr: arr,
                  towQuestionArr: arr,
                  towQuestionTotal: res.total,
                  drawerLoading: false,
                  isTowDrawer,
                });
              }
            } else {
              this.setState({
                questionArr: arr,
                questionsTotal: res.total,
                isTowDrawer,
              });
            }
          }
        });
    });
    // this.reqRef = requestAnimationFrame(() => {
    //   dispatch({
    //     type: 'editQa/getQuestionsByQaId',
    //     payload: { id: qaId, limit: limitNum, page: this.state.page, search: this.state.searchVal },
    //     callback: res => {
    //       const arr = [];
    //       for (const i of res.list) {
    //         arr.push(i.question);
    //       }
    //       if (isTowDrawer) {
    //         this.setState({
    //           towQuestionArr: arr,
    //           towQuestionTotal: res.total,
    //           drawerLoading: false,
    //           isTowDrawer,
    //         });
    //       } else {
    //         this.setState({
    //           questionArr: arr,
    //           questionsTotal: res.total,
    //           isTowDrawer,
    //         });
    //       }
    //     },
    //   });
    // });
  };

  getStandardQuestionByQaId = qaId => {
    const { dispatch } = this.props;

    const headData = {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${UserSession.getToken()}`,
    };
    return new Promise(resolve => {
      axios
        .post('/cloud/knowledge/base/getStandardQuestion', { id: qaId }, { headers: headData })
        .then(ret => {
          let res = null;
          if (ret.data.code) {
            this.checkStatus(ret.data.code);
          }
          if (ret.data.data) {
            res = ret.data.data;
            this.setState({
              standardQus: res.question,
            });
          }
        });
    });
    // this.reqRef = requestAnimationFrame(() => {
    //   dispatch({
    //     type: 'editQa/getStandardQuestionByQaId',
    //     payload: { id: qaId },
    //     callback: res => {
    //       this.setState({
    //         standardQus: res.question,
    //       });
    //     },
    //   });
    // });
  };

  getJsonAnswerByQaId = id => {
    const { dispatch, form } = this.props;

    const headData = {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${UserSession.getToken()}`,
    };
    return new Promise(resolve => {
      axios
        .post(
          '/cloud/knowledge/base/qa/answer',
          { qaId: id, isShared: this.state.shared, isSynchronous: this.state.synchronous },
          { headers: headData }
        )
        .then(ret => {
          const res = ret.data.data;
          if (ret.data.code) {
            this.checkStatus(ret.data.code);
          }
          for (const i of res) {
            i.isEdit = true;
          }
          if (res.length === 0) {
            res.push({
              isDefault: true,
              content: '',
              answerType: 'richText',
              slotValues: [],
              isEdit: false,
            });
          }
          this.setState({
            spinning: false,
            answerArr: res,
            answerArr_bak: res,
          });
        });
    });
    // this.reqRef = requestAnimationFrame(() => {
    //   dispatch({
    //     type: 'editQa/getJsonAnswerByQaId',
    //     payload: { qaId: id, isShared: this.state.shared, isSynchronous: this.state.synchronous },
    //     callback: res => {
    //       for (const i of res) {
    //         i.isEdit = true;
    //       }
    //       this.setState({
    //         spinning: false,
    //         answerArr: res,
    //         answerArr_bak: res,
    //       });
    //     },
    //   });
    // });
  };

  removeQuestion = (e, index) => {
    if (this.state.isShard) {
      return message.warn('共享的知识点不允许删除相似问');
    }
    const arr = this.state.questionArr;
    this.setState({
      questionArr: arr.filter(key => key !== e),
      towQuestionArr: arr.filter(key => key !== e),
    });
  };

  setStandard = e => {
    if (this.state.isShard) {
      return message.warn('共享的知识点不允许设置标准问');
    }
    const standard = this.state.standardQus;
    let arr = this.state.questionArr;
    arr = arr.filter(key => key !== e);
    arr.unshift(standard);
    this.setState({
      standardQus: e,
      questionArr: arr,
    });
  };

  modifiedStandard = val => {
    this.setState({
      standardQus: val,
    });
  };

  addSlotToNomalQuestion = name => {
    const value = `${this.state.standardQus}<${name}>`;
    this.setState({
      standardQus: value,
    });
  };

  addSlotToSmQuestion = (name, index) => {
    const { questionArr } = this.state;
    const value = `${questionArr[index]}<${name}>`;
    questionArr[index] = value;
    this.setState({
      questionArr,
    });
  };

  getQusBySearch = e => {
    const val = e.target.value;
    this.setState(
      {
        drawerLoading: true,
        searchVal: val,
      },
      () => {
        this.getQuestionsByQaid(this.state.qaId, true);
      }
    );
  };

  getQusBySearch1 = (val, page) => {
    this.setState(
      {
        drawerLoading: true,
        searchVal: val,
        page,
      },
      () => {
        this.getQuestionsByQaid(this.state.qaId, true);
      }
    );
  };

  showTotal = total => {
    return `共${total} 条`;
  };

  pageChange = num => {
    this.setState({
      page: num,
      drawerLoading: false,
    });
  };

  pageSizeChange = (current, size) => {
    this.setState({
      qusLimit: size,
      drawerLoading: false,
    });
  };

  pagination = (pageNo, pageSize, array) => {
    const offset = (pageNo - 1) * pageSize;
    return offset + pageSize >= array.length
      ? array.slice(offset, array.length)
      : array.slice(offset, offset + pageSize);
  };

  handleAdd = () => {
    const { slotArr, apiObj } = this.state;
    if (slotArr.length === 0) {
      return message.error('请先添加词槽');
    }

    const { apiDataSource, count } = this.state;
    const newData = {
      key: count,
      slotKey: '请选择词槽',
      apiFieldId: '请选择请求字段',
    };
    this.setState({
      apiDataSource: [...apiDataSource, newData],
      count: count + 1,
    });
  };

  handleDelete = key => {
    const dataSource = [...this.state.apiDataSource];
    this.setState({ apiDataSource: dataSource.filter(item => item.key !== key) });
  };

  fixData = (e, record, type) => {
    const { apiDataSource } = this.state;
    for (const i of apiDataSource) {
      if (i.key === record.key) {
        switch (type) {
          case 'apiFieldId':
            i.apiFieldId = e;
            break;
          case 'slotKey':
            i.slotKey = e;
            break;
        }
      }
    }
    this.setState({
      apiDataSource,
    });
  };

  setClassName = (record, index) => {
    return index < this.state.suggestionsLength ? styles.red : '';
  };

  onHistoryDrawerClose = () => {
    this.setState({
      historyDrawer: false,
    });
  };

  onHistoryDrawerOpen = () => {
    this.setState(
      {
        historyDrawer: true,
        getHistoryLoading: true,
      },
      () => {
        this.fetchQaFixHistoryByQaId(
          this.state.qaId,
          this.state.getHistoryPage,
          this.state.getHistoryLimit,
          ''
        );
      }
    );
  };

  fetchQaFixHistoryByQaId = (qaId, page, limit, query) => {
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/fetchQaFixHistoryByQaId',
        payload: { qaId, robotId: currentUser.robotId, page, limit, query },
        callback: res => {

          this.setState({
            getHistoryLoading: false,
            historyDataSource: res.items,
            historyDataSourceTotal: res.total,
          });
        },
      });
    });
  };

  getHistoryFanYe = e => {
    this.setState(
      {
        getHistoryPage: e,
      },
      () => {
        this.fetchQaFixHistoryByQaId(
          this.state.qaId,
          this.state.getHistoryPage,
          this.state.getHistoryLimit,
          ''
        );
      }
    );
  };

  getQaIdByReq = () => {
    const { dispatch } = this.props;
    const obj = {};
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'editQa/getQaId',
        payload: obj,
        callback: res => {
          this.setState({
            qaId: res.qaId,
          });
        },
      });
    });
    // const token =
    //   JSON.parse(window.localStorage.getItem('currentUser')) == undefined
    //     ? ''
    //     : JSON.parse(window.localStorage.getItem('currentUser')).token;
    // const headData = { 'Content-Type': 'application/json', token: token };
    // return new Promise(resolve => {
    //   axios.get('/knowledge/base/qaId', { headers: headData }).then(ret => {
    //     let res = null;
    //     if (ret.data.data) {
    //       res = ret.data.data;
    //     } else {
    //       return message.error(ret.data.msg);
    //     }
    //     this.setState({
    //       qaId: res.qaId,
    //     });
    //   });
    // });
  };

  onDragEnd(result) {
    // dropped outside the list
    if (!result.destination) {
      return;
    }

    const items = reorder(this.state.slotArr, result.source.index, result.destination.index);
    this.setState({
      slotArr: items,
    });
  }

  setSynchronization = e => {
    this.setState({
      synchronous: e,
    });
  };

  fixCommQus = val => {
    this.setState({
      commQus: val,
    });
  };

  fixSimQa = val => {
    this.setState({
      addSimqa: val,
    });
  };

  setSearchType = e => {

  };

  render() {
    const questionTotal = this.state.questionArr.length;
    let questionTow = [];
    if (this.state.isTowDrawer) {
      questionTow = this.pagination(
        this.state.page,
        this.state.qusLimit,
        this.state.towQuestionArr
      );
    } else {
      questionTow = this.pagination(this.state.page, this.state.qusLimit, this.state.questionArr);
    }
    const genExtra = (index, isDefault) => (
      <span>
        <Button
          type="primary"
          style={{ marginLeft: 10 }}
          icon="edit"
          size="small"
          onClick={event => {
            event.stopPropagation();
            this.onEditQa(index, 'edit');
          }}
          disabled={this.state.synchronous && isShard}
        >
          编辑
        </Button>
        {!isDefault ? (
          <Button
            type="danger"
            style={{ marginLeft: 10 }}
            icon="close"
            size="small"
            onClick={event => {
              event.stopPropagation();
              this.onEditQa(index, 'del');
            }}
            disabled={this.state.synchronous && isShard}
          >
            删除
          </Button>
        ) : (
          ''
        )}
      </span>
    );
    const slotList = this.state.slotArr;
    for (let i of slotList) {
      if (i.id) {
        i._id = i.id;
      }
    }
    const {
      qaStatus,
      questionArr,
      apiDataSource,
      apiObj,
      startTime,
      endTime,
      answerArr,
      saveQaLoading,
      getHistoryLoading,
      historyDataSource,
      historyDataSourceTotal,
      qaId,
      towQuestionTotal,
      isNew,
    } = this.state;
    const { isShard } = this.props;
    const apiColumns = [
      {
        title: '词槽',
        dataIndex: 'slotKey',
        width: '30%',
        render: (text, record) =>
          slotList.length >= 1 ? (
            <Select
              defaultValue="选择词槽"
              value={text}
              style={{ width: 200 }}
              onChange={e => this.fixData(e, record, 'slotKey')}
            >
              {slotList.map((slot, index) => {
                return <Option value={slot.key}>&lt;{slot.name}&gt;</Option>;
              })}
            </Select>
          ) : null,
      },
      {
        title: 'API字段-请求字段',
        dataIndex: 'apiFieldId',
        render: (text, record) => (
          <Select
            defaultValue="选择API请求字段"
            value={text}
            style={{ width: 200 }}
            onChange={e => this.fixData(e, record, 'apiFieldId')}
          >
            {apiObj.requestFields ? apiObj.requestFields.map((api, index) => {
              return <Option value={api.id}>#{api.name}#</Option>;
            }) : null}
          </Select>
        ),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        render: (text, record) =>
          this.state.apiDataSource.length >= 1 ? (
            <Popconfirm title="确认删除该列吗？" onConfirm={() => this.handleDelete(record.key)}>
              <Button type="primary" size="small" icon="delete">删除</Button>
            </Popconfirm>
          ) : null,
      },
    ];

    const ClassPageSize = this.state.classPageSize;

    const { currentUser } = this.props;
    return (
      <Suspense fallback={<PageLoading />}>
        <Spin tip="Loading..." spinning={this.state.spinning}>
          <Row gutter={16}>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ float: 'right' }}>
                <span
                  style={{ marginLeft: 10, cursor: 'pointer' }}
                  onClick={() => this.onHistoryDrawerOpen()}
                >
                  {' '}
                  <Icon type="clock-circle" theme="twoTone" /> 历史
                </span>
                <Button
                  disabled={this.state.synchronous && this.state.shared}
                  style={{ marginLeft: 10 }}
                  onClick={() => this.showModal('api')}
                >
                  添加Api接口
                </Button>

                <Button
                  disabled={this.state.synchronous && this.state.shared}
                  style={{ marginLeft: 10 }}
                  onClick={() => this.showModal('slot')}
                >
                  添加词槽
                </Button>
              </div>
            </div>
            <div>
              {this.state.isAddSlot ? (
                <div style={{ marginTop: 10 }}>
                  <div className={styles.label}>词槽</div>
                  <div className={styles.labelWarp}>
                    {slotList.map((slot, index) => {
                      return (
                        <Tag
                          closable
                          className={styles.slotTag}
                          key={slot.key}
                          onClose={e => this.delSlot(e, index, slot.name, slot._id)}
                        >
                          &lt;{slot.name}&gt;-{slot.key}
                        </Tag>
                      );
                    })}
                  </div>
                  {/* <DragDropContext onDragEnd={this.onDragEnd}>
                    <Droppable droppableId="droppable" direction="horizontal">
                      {(provided, snapshot) => (
                        <div
                          ref={provided.innerRef}
                          style={getListStyle(snapshot.isDraggingOver)}
                          {...provided.droppableProps}
                        >
                          {slotList.map((item, index) => (
                            <Draggable key={item._id} draggableId={item._id} index={index}>
                              {(provided, snapshot) => (
                                <div
                                  ref={provided.innerRef}
                                  {...provided.draggableProps}
                                  {...provided.dragHandleProps}
                                  style={getItemStyle(
                                    snapshot.isDragging,
                                    provided.draggableProps.style
                                  )}
                                >
                                  &lt;{item.name}&gt;-{item.key}
                                  <Icon
                                    type="close"
                                    onClick={e => this.delSlot(e, index, item.name, item._id)}
                                    style={{ marginLeft: 10, cursor: 'pointer', color: '#000' }}
                                  />
                                </div>
                              )}
                            </Draggable>
                          ))}
                          {provided.placeholder}
                        </div>
                      )}
                    </Droppable>
                  </DragDropContext>*/}
                </div>
              ) : (
                ''
              )}
              {this.state.isAddApi ? (
                <div style={{ marginTop: 10 }}>
                  <div className={styles.label}>API接口</div>
                  <div className={styles.labelWarp}>
                    <span>触发知识点时调用接口</span>
                    {this.state.isShowApiTag ? (
                      <span>
                        <Tag closable className={styles.apiTag} onClose={this.cleanApi}>
                          {this.state.apiObj.name}
                        </Tag>
                        <Icon
                          style={{ marginLeft: 10 }}
                          onClick={() => this.showModal('api')}
                          type="edit"
                        />
                      </span>
                    ) : (
                      ''
                    )}
                  </div>
                  <p style={{ color: 'grey', paddingLeft: 10 }}>词槽与字段的对应关系</p>
                  <Table
                    bordered
                    rowKey="key"
                    size="small"
                    pagination={false}
                    columns={apiColumns}
                    dataSource={apiDataSource}
                  />
                  <Button
                    onClick={this.handleAdd}
                    type="primary"
                    size="small"
                    icon="plus"
                    style={{ marginTop: 16 }}
                  >
                    添加
                  </Button>
                </div>
              ) : (
                ''
              )}
              <div style={{ marginTop: 10 }}>
                <div className={styles.label}>问题</div>
                <div className={styles.labelWarp}>
                  <QuestionList
                    slots={slotList}
                    isTowDrawer={false}
                    qaId={this.state.qaId}
                    add={value => this.add(value)}
                    isShard={isShard}
                    total={this.state.questionsTotal}
                    questions={this.state.qaId && !isNew ? questionArr.slice(0, 6) : questionArr}
                    standardQus={this.state.standardQus}
                    seeMore={() => this.showChildrenDrawer()}
                    isShowMore={questionArr.length > 6 && !isNew}
                    remove={(e, index) => this.removeQuestion(e, index)}
                    modifiQus={(e, k, index) => this.fixQuestion(e, k, index)}
                    modifiedStandard={val => this.modifiedStandard(val)}
                    getTopQus={e => this.getStandardQuestionByQaId(e)}
                    setStandardQus={(e, index) => this.setStandard(e, index)}
                    getQusList={id => this.getQuestionsByQaid(id, false)}
                    addSlotToNomalQuestion={name => this.addSlotToNomalQuestion(name)}
                    addSlotToSmQuestion={(name, index) => this.addSlotToSmQuestion(name, index)}
                    fixCommQuestion={val => this.fixCommQus(val)}
                    addSimqa={this.state.addSimqa}
                    modifiedSimQa={val => this.fixSimQa(val)}
                  />
                </div>
              </div>
              <div>
                <div>
                  <Row>
                    <Col span={4}>
                      <div className={styles.label}>答案</div>
                    </Col>
                    <Col span={4} offset={16}>
                      {isShard ? (
                        <div>
                          答案同步
                          <Switch
                            defaultChecked
                            checkedChildren="开启"
                            checked={this.state.synchronous}
                            style={{ marginLeft: 5 }}
                            unCheckedChildren="关闭"
                            onChange={this.setSynchronization}
                          />
                        </div>
                      ) : (
                        ''
                      )}
                      <div>
                        {this.state.slotArr.length > 0 && !isShard ? (
                          <Button
                            style={{ marginLeft: 10 }}
                            type="primary"
                            size="small"
                            icon="plus"
                            onClick={() => this.onEditQa(-1, 'add')}
                          >
                            添加答案
                          </Button>
                        ) : null}
                      </div>
                    </Col>
                  </Row>
                </div>

                <div className={styles.labelWarp}>
                  {answerArr.map((answer, index) => {
                    return (
                      <div key={index}>
                        {!answer.isEdit ? (
                          <div className={styles.answerWarp}>
                            {answer.isDefault ? (
                              <Row>
                                <Col span={5}>{index === 0 ? ' ' : ' 其它情况默认答案'}</Col>
                                <Col span={5} offset={14}>
                                  <Button style={{ marginLeft: 7 }} onClick={() => this.onEditQa(index, 'cancel')}>取消</Button>
                                  <Button type="primary" style={{ marginLeft: 10, float: 'right' }} onClick={() => this.onEditQa(index, 'save')}>完成</Button>
                                </Col>
                              </Row>
                            ) : (
                              <Row>
                                <Col span={15}>
                                  {this.state.slotDetailArr.map((slotDetailItem, slotIndex) => {
                                    return (
                                      <Row style={{ marginTop: 10 }}>
                                        {slotDetailItem.isEnum ? (
                                          <div>
                                            <Col span={4} style={{ textAlign: 'right' }}>{slotDetailItem.name}:</Col>
                                            <Col span={18} offset={1}>
                                              {answer.slotValues.length > 0 ? (
                                                <Select
                                                  mode="multiple"
                                                  style={{ width: '100%' }}
                                                  placeholder="请选择词槽"
                                                  onBlur={value => this.addSlotForSelect(value, index, slotIndex, slotDetailItem.id, slotDetailItem.name)}
                                                  onDeselect={value => this.editSlotByUnSelect(value, index, slotIndex, slotDetailItem.id, slotDetailItem.name)}
                                                  defaultValue={slotDetailItem.values}
                                                  key={slotIndex}
                                                >
                                                  {slotDetailItem.items.map(function(item, itemIndex) {
                                                    return (
                                                      <Option key={item.word}>{item.word}</Option>
                                                    );
                                                  })}
                                                </Select>
                                              ) : (
                                                <Select
                                                  mode="multiple"
                                                  style={{ width: '100%' }}
                                                  placeholder="请选择词槽"
                                                  onDeselect={value => this.editSlotByUnSelect(value, index, slotIndex, slotDetailItem.id, slotDetailItem.name)}
                                                  onBlur={value => this.addSlotForSelect(value, index, slotIndex, slotDetailItem.id, slotDetailItem.name)}
                                                  key={slotIndex}
                                                >
                                                  {slotDetailItem.items.map(function(item, itemIndex) {
                                                    return (
                                                      <Option key={item.word}>{item.word}</Option>
                                                    );
                                                  })}
                                                </Select>
                                              )}
                                            </Col>
                                          </div>
                                        ) : (
                                          <div>
                                            <Col span={4} style={{ textAlign: 'right' }}>{slotDetailItem.name}:</Col>
                                            <Col span={18} offset={1}>
                                              <span style={{ color: 'lightgrey' }}>词槽值不可枚举，不支持设置条件</span>
                                            </Col>
                                          </div>
                                        )}
                                      </Row>
                                    );
                                  })}
                                </Col>
                                <Col span={5} offset={4}>
                                  <Button style={{ marginLeft: 10 }} onClick={() => this.onEditQa(index, 'cancel')}>取消</Button>
                                  <Button style={{ marginLeft: 10 }} onClick={() => this.onEditQa(index, 'save')}>保存</Button>
                                </Col>
                              </Row>
                            )}
                            <Row>
                              <Tabs
                                type="card"
                                defaultActiveKey={answer.answerType}
                                onChange={key => this.callback(key, index)}
                                style={{ marginTop: 10 }}
                              >
                                <TabPane tab="富文本" key="richText">
                                  <div style={{ width: 700 }}>
                                    <Editor
                                      content={answer.content}
                                      name={`content${index}`}
                                      id={`content${index}`}
                                      ref={`content${index}`}
                                    />
                                  </div>
                                </TabPane>
                                <TabPane tab="文本" key="text">
                                  <TextArea
                                    rows={6}
                                    onChange={e => this.getTextValue(e, index)}
                                    defaultValue={answer.content}
                                  />
                                </TabPane>
                              </Tabs>
                            </Row>
                          </div>
                        ) : (
                          <div>
                            <Collapse
                              defaultActiveKey={this.state.qaActiveKeys}
                              expandIconPosition={this.state.expandIconPosition}
                              style={{ marginTop: 10 }}
                            >
                              {!answer.isDefault ? (
                                <Panel
                                  header={answer.slotValues.map((slotValueItem, slotValueIndex) => {
                                    return (
                                      <span key={slotValueIndex}>
                                        &lt;{slotValueItem.slotName}&gt;=
                                        <Tag color="#108ee9">
                                          {slotValueItem.values.map((tag, tagIndex) => {
                                            return (
                                              <span key={tagIndex} style={{ marginLeft: 5, marginRight: 5 }}>{tag}</span>
                                            );
                                          })}
                                        </Tag>
                                      </span>
                                    );
                                  })}
                                  key={index}
                                  extra={genExtra(index, answer.isDefault)}
                                >
                                  <div
                                    className={styles.previewAnswer}
                                    dangerouslySetInnerHTML={{ __html: answer.content }}
                                  />
                                </Panel>
                              ) : (
                                <Panel
                                  header="普通答案"
                                  key={index}
                                  extra={genExtra(index, answer.isDefault)}
                                >
                                  <div
                                    className={styles.commAnwer}
                                    dangerouslySetInnerHTML={{ __html: answer.content }}
                                  />
                                </Panel>
                              )}
                            </Collapse>
                          </div>
                        )}
                      </div>
                    );
                  })}
                </div>
              </div>
              <div>
                <Row>
                  <Col span={4}>
                    <div className={styles.label}>关联问题</div>
                  </Col>
                  <Col span={2} offset={16}>
                    <div>
                      <Button
                        disabled={this.state.synchronous && this.state.shared}
                        style={{ marginLeft: 10 }}
                        type="primary"
                        size="small"
                        onClick={() => this.addLinkQa()}
                      >
                        添加关联知识点
                      </Button>
                    </div>
                  </Col>
                </Row>
                <div className={styles.labelWarp}>
                  {this.state.relateList.map((qa, qaIndex) => {
                    return (
                      <div style={{ marginTop: 10 }} key={qaIndex}>
                        <Row>
                          <Col span={22}>
                            <Input
                              value={qa.question}
                              key={qaIndex}
                              disabled
                              className={styles.relateQa}
                            />
                          </Col>
                          <Col span={2}>
                            <Icon
                              className="dynamic-delete-button"
                              type="close-circle"
                              onClick={() => this.onDelRelateQa(qaIndex, qa)}
                              style={{
                                fontSize: 20,
                                marginLeft: 10,
                                cursor: 'pointer',
                                marginTop: 5,
                              }}
                            />
                            {qaIndex > 0 ? (
                              <Icon
                                type="arrow-up"
                                onClick={() => this.onSetRelateQa(qaIndex)}
                                style={{
                                  fontSize: 20,
                                  marginLeft: 10,
                                  cursor: 'pointer',
                                  marginTop: 5,
                                }}
                              />
                            ) : (
                              ''
                            )}
                          </Col>
                        </Row>
                      </div>
                    );
                  })}
                </div>
              </div>
              <div>
                <Row>
                  <Col span={4}>
                    <div className={styles.label}>知识点分类</div>
                  </Col>
                </Row>
                <div className={styles.labelWarp}>
                  <Row>
                    <Col span={3}>选择分类</Col>
                    <Col span={8}>
                      <TreeSelect
                        showSearch
                        allowClear
                        treeDefaultExpandAll
                        disabled={isShard}
                        style={{ width: 300 }}
                        treeNodeFilterProp="title"
                        value={this.state.categoryId ? this.state.categoryId : 'root'}
                        placeholder="点击选择知识点分类"
                        treeDefaultExpandedKeys={['root']}
                        showCheckedStrategy={TreeSelect.SHOW_ALL}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        onChange={(value, label, extra) => this.onTreeChange(value, label, extra)}
                        // onFocus={()=>this.getCategoryListJson()}
                      >
                        {this.renderTreeNodes(this.state.treeData)}
                      </TreeSelect>
                    </Col>
                  </Row>
                </div>
              </div>
              <div>
                <Row>
                  <Col span={4}>
                    <div className={styles.label}>生效时间</div>
                  </Col>
                </Row>
                <div className={styles.labelWarp}>
                  <Row>
                    <Col span={3}>知识点状态</Col>
                    <Col span={8}>
                      <Switch
                        checkedChildren="启用"
                        disabled={this.state.synchronous && this.state.shared}
                        unCheckedChildren="禁用"
                        checked={qaStatus}
                        onChange={this.onChangeQaStatus}
                      />
                    </Col>
                  </Row>
                  {this.state.disabled ? (
                    ''
                  ) : (
                    <div>
                      <Row style={{ marginTop: 10 }}>
                        <Col span={3}>知识点有效期</Col>
                        <Col span={8}>
                          <RadioGroup
                            onChange={this.onChangeQaIsForever}
                            disabled={this.state.synchronous && this.state.shared}
                            value={this.state.isForever}
                          >
                            <Radio value>永久有效</Radio>
                            <Radio value={false}>自定义有效期</Radio>
                          </RadioGroup>
                        </Col>
                      </Row>
                      <Row style={{ marginTop: 10 }}>
                        <Col span={16} offset={3}>
                          {!this.state.isForever ? (
                            <div>
                              <DatePicker
                                allowClear={false}
                                format="YYYY-MM-DD "
                                placeholder="开始日期"
                                onChange={this.onStartChange}
                                disabled={this.state.synchronous && this.state.shared}
                                onOpenChange={this.handleStartOpenChange}
                                value={moment(
                                  startTime === '' ? new Date() : startTime,
                                  dateFormat
                                )}
                              />
                              <span style={{ margin: '0 10px' }}>至</span>
                              <DatePicker
                                allowClear={false}
                                format="YYYY-MM-DD "
                                placeholder="结束日期"
                                open={this.state.endOpen}
                                onChange={this.onEndChange}
                                disabled={this.state.synchronous && this.state.shared}
                                onOpenChange={this.handleEndOpenChange}
                                value={moment(endTime === '' ? new Date() : endTime, dateFormat)}
                              />
                            </div>
                          ) : (
                            ''
                          )}
                        </Col>
                      </Row>
                    </div>
                  )}
                </div>
              </div>
              <div>
                <Row style={{ marginTop: 30 }}>
                  <Col span={8} offset={3}>
                    <Button onClick={this.cancelSaveQa} style={{ marginRight: 10 }}>取消</Button>
                    <Button type="primary" loading={saveQaLoading} onClick={() => this.saveQa()}>{saveQaLoading ? '保存中' : '保存'}</Button>
                  </Col>
                </Row>
              </div>
            </div>
          </Row>
        </Spin>
        <Modal
          visible={this.state.visible}
          title={this.state.modalTitle}
          onCancel={this.handleCancel}
          footer={[
            <Pagination
              defaultCurrent={1}
              defaultPageSize={5}
              onChange={e => this.fanye(e)}
              total={parseInt(this.state.total)}
              size="small"
            />,
          ]}
          width={350}
          key={123}
          centered
        >
          <div>
            <Search
              placeholder={this.state.placeholder}
              onSearch={value => this.modalSearch(value, 1)}
              value={this.state.keys}
              style={{ width: 200 }}
              onChange={this.slotAndApiSearch}
            />
            <Button style={{ marginLeft: 10 }} onClick={() => this.newCreate()}>新建</Button>
          </div>
          <div className={styles.modalBody}>
            <Spin spinning={this.state.addLoading}>
              {this.state.list.map((api, index) => {
                return (
                  <div className={styles.modalItem} key={index}>
                    <Button size="small" type="primary" onClick={() => this.selected(api)}>选择</Button>
                    {this.state.type === 'api' ? (
                      <span style={{ marginLeft: 10 }}>{api.name}</span>
                    ) : (
                      <span style={{ marginLeft: 10 }}>
                        &lt;{api.key}&gt; ({api.name})
                      </span>
                    )}
                  </div>
                );
              })}
            </Spin>
          </div>
        </Modal>
        <Drawer
          title="返回"
          width={700}
          closable
          destroyOnClose
          onClose={this.onChildrenDrawerClose}
          visible={this.state.childrenDrawer}
        >
          <Spin spinning={this.state.drawerLoading}>
            <QuestionList
              slots={slotList}
              isShowMore={false}
              isTowDrawer
              isShard={isShard}
              qaId={this.state.qaId}
              questions={questionTow}
              add={value => this.add(value)}
              search={e => this.getQusBySearch(e)}
              search1={(val, page) => this.getQusBySearch1(val, page)}
              standardQus={this.state.standardQus}
              seeMore={() => this.showChildrenDrawer()}
              remove={(e, index) => this.removeQuestion(e, index)}
              getTopQus={e => this.getStandardQuestionByQaId(e)}
              modifiQus={(e, k, index) => this.fixQuestion(e, k, index)}
              modifiedStandard={val => this.modifiedStandard(val)}
              setStandardQus={(e, index) => this.setStandard(e, index)}
              getQusList={id => this.getQuestionsByQaid(id, true)}
              addSlotToNomalQuestion={name => this.addSlotToNomalQuestion(name)}
              addSlotToSmQuestion={(name, index) => this.addSlotToSmQuestion(name, index)}
              fixCommQuestion={val => this.fixCommQus(val)}
              addSimqa={this.state.addSimqa}
              modifiedSimQa={val => this.fixSimQa(val)}
            />
          </Spin>
          <div style={{ overflow: 'hidden' }}>
            <Pagination
              size="small"
              showSizeChanger
              showQuickJumper
              total={parseInt(towQuestionTotal)}
              style={{ float: 'right' }}
              current={this.state.page}
              defaultPageSize="10"
              showTotal={() => this.showTotal(questionTotal)}
              onChange={pageNumber => this.pageChange(pageNumber)}
              onShowSizeChange={(current, size) => this.pageSizeChange(current, size)}
            />
          </div>
        </Drawer>
        <Drawer
          title="返回"
          width={700}
          closable
          destroyOnClose
          onClose={this.onHistoryDrawerClose}
          visible={this.state.historyDrawer}
        >
          <Table
            rowKey="qaId"
            bordered
            dataSource={historyDataSource}
            columns={this.historyColumns}
            loading={getHistoryLoading}
            pagination={{
              // 分页
              total: parseInt(historyDataSourceTotal), // 数据总数量
              pageSize: 10, // 显示几条一页
              showSizeChanger: false, // 是否显示可以设置几条一页的选项
              onChange: e => this.getHistoryFanYe(e),
              showQuickJumper: true,
            }}
          />
        </Drawer>
        <Modal
          visible={this.state.classVisible}
          title="选择关联问题"
          onCancel={this.classHandleCancel}
          footer={[]}
          width={750}
          key="2"
          centered
        >
          <Form layout="inline" style={{ paddingBottom: 20 }}>
            <FormItem>
              <Select
                style={{ width: 160 }}
                defaultValue={this.state.classField}
                onChange={this.classSelectChange}
              >
                <Option value="q">搜索问题</Option>
                <Option value="a">搜索答案</Option>
              </Select>
            </FormItem>
            <FormItem>
              <Search
                placeholder="请输入内容"
                onSearch={value => this.searchClass(value)}
                style={{ width: 320 }}
                allowClear
              />
            </FormItem>
          </Form>
          <Spin spinning={this.state.loading}>
            <Table
              style={{ height: 500, overflow: 'auto' }}
              size="small"
              columns={this.columns}
              // rowClassName={this.setClassName}
              dataSource={this.state.linkData} // 数据
              rowKey="sid"
              pagination={{
                // 分页
                total: parseInt(this.state.total), // 数据总数量
                pageSize: ClassPageSize, // 显示几条一页
                showSizeChanger: true, // 是否显示可以设置几条一页的选项
                onChange: e => this.fanye(e, 'class'),
                onShowSizeChange: this.onShowSizeChange,
                showQuickJumper: true,
              }}
            />
          </Spin>
        </Modal>
        <Modal
          width="calc(80vw)"
          height="calc(80vh)"
          visible={this.state.imgHide}
          title="图片详情"
          onCancel={() => {
            this.setState({
              imgHide: false,
            });
          }}
          footer={null}
        >
          {<div dangerouslySetInnerHTML={{ __html: this.state.img }} />}
        </Modal>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(EditQa));
